package com.example.huixingzheng.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.huixingzheng.R;
import com.example.huixingzheng.adapter.DeviceAdapter;
import com.example.huixingzheng.bean.Device;

import java.util.ArrayList;
import java.util.List;

public class DeviceActivity extends AppCompatActivity {

    private RecyclerView rvDeviceList;
    private DeviceAdapter deviceAdapter;
    private List<Device> deviceList;       // 原始列表
    private List<Device> filteredList;     // 过滤后列表

    private EditText etSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device);

        // 初始化控件
        rvDeviceList = findViewById(R.id.recyclerView);
        etSearch = findViewById(R.id.et_search);

        // 模拟一些设备数据
        deviceList = new ArrayList<>();
        deviceList.add(new Device("一号设备", 25.3f, 60.5f, 300, 20));
        deviceList.add(new Device("二号设备", 27.0f, 55.2f, 450, 25));
        deviceList.add(new Device("三号设备", 24.8f, 63.0f, 200, 15));
        // …可继续添加

        // 默认先全部显示
        filteredList = new ArrayList<>(deviceList);

        // 初始化适配器
        deviceAdapter = new DeviceAdapter(filteredList);

        // 设置RecyclerView
        rvDeviceList.setLayoutManager(new LinearLayoutManager(this));
        rvDeviceList.setAdapter(deviceAdapter);

        // 给搜索框添加文本变化监听，实现简单的搜索功能
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 不需要实现
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                filterDevices(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 不需要实现
            }
        });
    }

    /**
     * 根据输入关键字过滤设备列表
     */
    private void filterDevices(String keyword) {
        filteredList.clear();
        if (keyword.isEmpty()) {
            filteredList.addAll(deviceList);
        } else {
            for (Device device : deviceList) {
                if (device.getName().contains(keyword)) {
                    filteredList.add(device);
                }
            }
        }
        deviceAdapter.notifyDataSetChanged();
    }


}